<template>
  <div class="user pb50" v-loading="loading">
    <div class="product-content">
      <!--售后单信息-->
      <div class="common-form">售后单信息</div>
      <div class="refund-detail-content">
        <el-row>
          <el-col :span="5">
            <div class="pb16">
              <span class="gray9">订单号：</span>
              {{ detail.order.orderNo }}
            </div>
          </el-col>
          <el-col :span="5">
            <div class="pb16">
              <span class="gray9">买家：</span>
              {{ detail.user.nickName }}
            </div>
          </el-col>
          <el-col :span="5">
            <div class="pb16">
              <span class="gray9">售后类型：</span>
              {{ detail.typeText }}
            </div>
          </el-col>
          <el-col :span="5">
            <div class="pb16">
              <span class="gray9">处理状态：</span>
              {{ detail.statusText }}
            </div>
          </el-col>
          <el-col :span="4">
            <div class="pb16">
              <el-button size="small" href="/" target="_blank" @click="gotoPage(detail)">订单详情</el-button>
              <el-button size="small" style="border-radius: 50%;
    position: fixed;
    right: 3%;
    bottom: 15%;
    z-index: 9999;" type="success" v-if="detail.flowInfoList && detail.flowInfoList.length"
                @click="showPic(detail)">流程图</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <!--售后商品信息-->
      <div class="common-form">售后商品信息</div>
      <el-table :data="detail.orderProductList" :border="true">
        <el-table-column prop="productNo" label="图片">
          <template #default="scope">
            <div v-if="scope.row.imagePath"> <img :src="scope.row.imagePath" style="width:60px;height:60px" /></div>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
        <el-table-column prop="productAttr" label="规格属性" width="300"></el-table-column>
        <el-table-column prop="productPrice" label="单价"></el-table-column>
        <el-table-column prop="totalNum" label="购买数量"></el-table-column>
        <el-table-column prop="expectDeliveryTime" label="预计发货日期"></el-table-column>
        <el-table-column prop="productAddress" label="生产部门"></el-table-column>
      </el-table>
      <!--用户申请原因-->
      <div class="apply-reason-box">
        <div class="common-form">用户申请原因</div>
        <div class="apply-reason">{{ detail.applyDesc }}</div>
        <div class="d-s-s mt10" v-if="detail && detail.images && detail.images.length > 0">
          <div class="pic" v-for="(item, index) in detail.images" :key="index">
            <img v-img-url="item.filePath" alt="" width="60" />
          </div>
        </div>
      </div>

      <div class="apply-reason-box" v-if="detail.refuseDesc || detail.financeRefuseDesc">
        <div class="common-form">单据拒绝原因： </div>
        <div class="apply-reason">{{ detail.refuseDesc || detail.financeRefuseDesc }}</div>
      </div>
      <div v-if="detail.type === 10 && detail.address">
        <div class="common-form">物流信息</div>
        <div class="refund-detail-content">
          <el-row>
            <el-col :span="5">
              <div class="pb16">
                <span class="gray9">物流公司： </span>
                {{ detail.express.expressName }}
              </div>
            </el-col>
            <el-col :span="5">
              <div class="pb16">
                <span class="gray9">物流单号：</span>
                {{ detail.expressNo }}
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="common-form">收货人信息</div>
        <div class="refund-detail-content">
          <el-row>
            <el-col :span="5">
              <div class="pb16">
                <span class="gray9">收货人姓名： </span>
                {{ detail.address.name }}
              </div>
            </el-col>
            <el-col :span="5">
              <div class="pb16">
                <span class="gray9">收货人联系方式：</span>
                {{ detail.address.phone }}
              </div>
            </el-col>
            <el-col :span="8">
              <div class="pb16">
                <span class="gray9">收货人联系地址：</span>
                {{ detail.address.detail }}
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <!-- 最新审核页面 -->
      <div>
        <div class="common-form mt16">审核</div>
        <el-form size="small" ref="form" :model="form" label-width="100px">
          <el-form-item label="退款金额">
            <el-input-number v-model="detail.refundMoney" disabled :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="退款方式">

            <el-radio-group disabled v-model="detail.refundMoneyType">
              <el-radio :label="10">全部退款</el-radio>
              <el-radio :label="20">部分退款</el-radio>
              <el-radio :label="30">超额退款</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="退还方式">

            <el-radio-group disabled v-if="detail.backType == 20" v-model="detail.backType">
              <el-radio :label="20">余额退回</el-radio>
              <el-radio :label="30">银行转账</el-radio>

            </el-radio-group>
            <el-radio-group disabled v-else v-model="detail.backType">
              <el-radio :label="10">原路退回</el-radio>
              <el-radio :label="20">余额退回</el-radio>
              <el-radio :label="30">银行转账</el-radio>

            </el-radio-group>
          </el-form-item>
          <div>
            <el-form-item label="审核状态">
              <el-radio-group :disabled="!detail.auditBtn" v-model="form.auditType">
                <el-radio :label="10">同意</el-radio>
                <el-radio :label="20">拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="拒绝原因" v-if="form.auditType == 20">
              <el-input type="textarea" v-model="form.auditDesc" class="max-w460"></el-input></el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 审核最新 -->
      <!-- <div style="margin-bottom: 40px;" v-if="detail.auditBtn">
        <div class="common-form mt16">审核</div>
        <p>
          操作：
          <el-radio-group v-model="OrderAuditForm.auditType">
            <el-radio :label="10">同意</el-radio>
            <el-radio :label="20">拒绝</el-radio>
          </el-radio-group>
        </p>
        <p v-if="OrderAuditForm.auditType === 20">
          拒绝原因：
          <el-input type="textarea" style="width: 50%;" v-model="OrderAuditForm.auditDesc" />
        </p>
      </div> -->
    </div>
    <!-- 最新按钮 -->
    <div class="common-button-wrapper">
      <el-button size="small" type="info" @click="cancelFunc">取消 / 返回上一页</el-button>
      <div style="margin:0px 10px">
        <el-button size="small" type="primary" v-if="detail.auditBtn" @click="OrderAudit(detail.orderRefundId)"
          :loading="OrderAuditLoading">确认审核</el-button>
      </div>
    </div>
    <!-- 
    <div class="common-button-wrapper" v-if="detail.type === 10">
      <el-button size="small" type="info" @click="cancelFunc">取消 / 返回上一页</el-button>
      <div style="margin:0px 10px">
        <el-button size="small" type="primary" v-if="detail.flowStatus === 10 && detail.status !== 20"
          v-auth="'/order/refund/audit'" @click="ywyThOneStep(detail.orderRefundId)"
          :loading="oneStepLoading">确认审核-业务员</el-button>
      </div>
      <div style="margin:0px 10px">
        <el-button size="small" type="primary" v-if="detail.flowStatus === 30 && detail.status !== 20"
          v-auth="'/order/refund/delivery/audit'" @click="ywyThTwoStep(detail.orderRefundId)"
          :loading="oneStepLoading">确认审核-业务员退款</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" v-if="detail.flowStatus === 40 && detail.status !== 20"
          v-auth="'/order/refund/receipt'" :loading="oneStepLoading"
          @click="cwTwoStep(detail.orderRefundId)">确认审核-财务确认</el-button>
      </div>
    </div>
    <div class="common-button-wrapper" v-if="detail.type === 30">
      <el-button size="small" type="info" @click="cancelFunc">取消 / 返回上一页</el-button>
      <div style="margin: 0px 10px;" v-if="detail.flowStatus === 31 && detail.status !== 10 && detail.status !== 20"
        v-auth="'/order/refund/xszjaudit'">
        <el-button size="small" type="primary" :loading="xzzjLoading" @click="xszjAudit(detail.orderRefundId)">
          销售总监审核
        </el-button>
      </div>
      <div style="margin: 0px 10px;" v-if="detail.flowStatus === 32 && detail.status !== 10 && detail.status !== 20"
        v-auth="'/order/refund/jdaudit'">
        <el-button size="small" type="primary" :loading="scjdLoading" @click="jdAudit(detail.orderRefundId)">
          基地审核
        </el-button>
      </div>
      <div style="margin:0px 10px">
        <el-button size="small" type="primary"
          v-if="detail.flowStatus === 30 && detail.status !== 10 && detail.status !== 20" v-auth="'/order/refund/audit'"
          @click="ywyOneStep(detail.orderRefundId)" :loading="oneStepLoading">确认审核-业务员</el-button>
      </div>
      <div>
        <el-button size="small" type="primary"
          v-if="detail.flowStatus === 40 && detail.status !== 10 && detail.status !== 20" :loading="oneStepLoading"
          v-auth="'/order/refund/receipt'" @click="cwTwoStep(detail.orderRefundId)">确认审核-财务确认</el-button>
      </div>
    </div> -->
    <el-dialog title="流程审批图" v-model="dialogPicVisible" @close="dialogPicVisible = false" :close-on-click-modal="false"
      :close-on-press-escape="false" width="70%">
      <!--内容-->
      <div>
        <josnToProcess :list="flowInfoList">
          <template #default="{ items }">
            <div class="node_item" style="font-weight: bold;">
              【{{ items.stepName }}】
            </div>
            <div>
              <p v-if="items.auditPerson || items.assignee">审核人: {{ items.auditPerson || items.assignee }}</p>
              <p v-if="items.auditTime">审核时间: {{ items.auditTime }}</p>
              <!-- 0-待审批 10-审批中  20-通过 30-拒绝 -->
              <p v-if="items.status">审核状态: <el-tag :type="items.status == '10' ? 'warning' : items.status == '20' ? 'success' : items.status == '30' ? 'danger' :
                'info'"> {{ items.status == '10' ? '审批中' : items.status == '20' ? '通过' : items.status == '30' ? '拒绝' :
                  '待审批' }}</el-tag>
              </p>
            </div>
          </template>
        </josnToProcess>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import OrderApi from "@/api/order.js";
import { ElMessage } from "element-plus";
import josnToProcess from "@/components/flow-pic.vue"
export default {
  components: {
    josnToProcess
  },
  data() {
    return {
      tableData: {},
      btnLoading: false,
      xzzjLoading: false,
      scjdLoading: false,
      OrderAuditForm: {},
      OrderAuditLoading: false,
      dialogPicVisible: false,
      flowInfoList: [],
      picJson: [],
      /*退货详情*/
      detail: {
        isAgree: {},
        type: {},
        status: {},
        order: {},
        user: {},
        orderProduct: {},
        express: {},
        address: {},
        image: [],
        is_plate_send: 0,
        sendexpress: {},
      },
      /*快递公司列表*/
      expressList: [],
      /*订单详情*/
      order: {},
      /*退货地址列表*/
      addressList: {},
      form: {
        auditType: 10,
        addressId: "",
        refuseDesc: "",
        refundMoney: "",
        cwfundMoney: 0,
        financeRefundMoney: 0
      },
      money: {
        refundMoney: "",
      },
      orderRefundId: 0,
      deliver: {
        sendExpressId: "",
        sendExpressNo: "",
      },
      loading: true,
      oneStepLoading: false,
      flowStatus: 0  // 10 第一次审核  30 业务员第二次审核  40 财务审核 
    };
  },
  created() {
    /*获取列表*/
    this.getData();
  },
  methods: {
    showPic() {
      this.dialogPicVisible = true;
    },
    /*获取列表*/

    getData() {
      let $this = this;
      let order_refund_id = $this.$route.query.orderRefundId;
      OrderApi.refundDetail(
        {
          orderRefundId: order_refund_id,
        },
        true
      )
        .then((res) => {
          console.log('详情', res.data)
          $this.detail = res.data;
          $this.order = res.data.order;
          $this.addressList = res.data.addressList;
          $this.expressList = res.data.expressList;
          $this.form.refundMoney = Number(res.data.refundMoney)
          $this.form.cwfundMoney = Number(res.data.refundMoney)
          $this.loading = false;
          $this.flowInfoList = $this.flowInfoListFunc($this.detail.flowInfoList)
        })
        .catch((error) => { });
    },
    // 流程图审批数据结构
    flowInfoListFunc(flowInfoList = []) {
      let Arr = [{
        stepName: '订单审批流程图',
        children: []
      }]
      if (flowInfoList && flowInfoList.length) {
        flowInfoList.map((val, index) => {
          val['id'] = index++;
          if (val.nodeList && val.nodeList.length == 1) {
            val['auditPerson'] = val.nodeList[0].auditPerson
            val['assignee'] = val.nodeList[0].assignee
            val['auditTime'] = val.nodeList[0].auditTime
            val['status'] = val.nodeList[0].status
          } else {
            val.nodeList.map((item, dex) => {
              item['id'] = index++ + '-' + dex++
              item['stepName'] = item.nodeName
            })
            val['children'] = val.nodeList
          }
        })
        Arr[0].children = flowInfoList
        console.log(Arr, 'Arr')

        return Arr
      }
    },
    /*跳转订单详情*/
    gotoPage(row) {
      let self = this;

      this.$router.push({
        path: "/order/order/detail",
        query: {
          id: row.orderId,
          tk: 'view'
        },
      });
    },
    xszjAudit(id) {
      const $this = this
      const postBody = {
        isAgree: $this.form.isAgree,
        orderRefundId: id,
        refuseDesc: $this.form.refuseDesc,
        refundMoney: $this.form.refundMoney
      }
      $this.xzzjLoading = true
      OrderApi.xszjAudit(postBody, true)
        .then(result => {
          $this.xzzjLoading = false
          const { code, msg } = result
          if (code === 1) {
            ElMessage.success(msg)
            $this.getData()
          } else {
            ElMessage.error(msg)
          }
        }).catch(error => {
          $this.xzzjLoading = false
        }
        )
      console.log('ids', postBody)
    },
    jdAudit(id) {
      const $this = this
      const postBody = {
        isAgree: $this.form.isAgree,
        orderRefundId: id,
        refuseDesc: $this.form.refuseDesc,
        refundMoney: $this.form.refundMoney
      }
      $this.scjdLoading = true
      OrderApi.scjdAudit(postBody, true)
        .then(result => {
          $this.scjdLoading = false
          const { code, msg } = result
          if (code === 1) {
            ElMessage.success(msg)
            $this.getData()
          } else {
            ElMessage.error(msg)
          }
        }).catch(error => {
          $this.scjdLoading = false
        })
      console.log('ids', postBody)
    },
    ywyOneStep(e) {
      //退货-业务员第一步审批
      const $this = this
      const postBody = {
        orderRefundId: e,
        isAgree: $this.form.isAgree,
        refuseDesc: $this.form.refuseDesc,
        refundMoney: $this.form.refundMoney
      }
      if (postBody.isAgree === 20
        && !postBody.refuseDesc
      ) {
        ElMessage.error('请输入拒绝原因')
        return
      }
      // if (postBody.isAgree === 10 
      //   && postBody.refundMoney<=0
      // ) {
      //   ElMessage.error('退款金额不合法')
      //   return 
      // }
      console.log('pobody', postBody)
      $this.oneStepLoading = true
      OrderApi.ShAudit(postBody, true)
        .then(result => {
          $this.oneStepLoading = false
          const { code, msg } = result
          if (code === 1) {
            $this.getData()
            ElMessage.success(msg)
          } else {
            ElMessage.error(msg)
          }
        }).catch(error => {
          $this.oneStepLoading = false
        })
    },
    // 财务审核确认
    cwTwoStep(e) {
      //退货-财务审核
      const $this = this
      const postBody = {
        orderRefundId: e,
        isAgree: $this.form.isAgree,
        refuseDesc: $this.form.refuseDesc,
        refundMoney: $this.form.cwfundMoney,
        backType: $this.form.backType
      }
      if (postBody.isAgree === 20
        && !postBody.refuseDesc
      ) {
        ElMessage.error('请输入拒绝原因')
        return
      }
      if (postBody.isAgree === 10
        && postBody.refundMoney <= 0
      ) {
        ElMessage.error('退款金额不合法')
        return
      }
      $this.oneStepLoading = true
      OrderApi.cwAudit(postBody, true)
        .then(result => {
          $this.oneStepLoading = false
          const { code, msg } = result
          if (code === 1) {
            $this.getData()
            ElMessage.success(msg)
          } else {
            ElMessage.error(msg)
          }
        }).catch(error => {
          $this.oneStepLoading = false
        })

      console.log('第一步', postBody)


    },
    // 最新审核
    // 订单审核
    OrderAudit() {
      let Obj = {
        orderId: this.detail.orderId,
        orderFlowId: this.detail.orderFlowId,
        auditType: this.form.auditType,
        auditDesc: this.form.auditDesc,
      }
      this.OrderAuditLoading = true
      OrderApi.orderAuditV2(Obj).then(result => {
        this.OrderAuditLoading = false
        const { code, msg } = result
        if (code === 1) {
          ElMessage.success(msg)
          this.getData();
          this.$emit('OrderDetailsAudit')
        } else {
          ElMessage.error(msg)
        }
      }).catch(error => {
        this.OrderAuditLoading = false
      })
    },
    ywyThOneStep(e) {
      // 退货退款-业务员
      const $this = this
      const postBody = {
        isAgree: $this.form.isAgree,
        orderRefundId: e,
        refuseDesc: $this.form.refuseDesc,
        addressId: $this.form.addressId
      }
      if (postBody.isAgree === 10
        && !postBody.addressId
      ) {
        ElMessage.error('请选择退货地址')
        return
      }
      if (postBody.isAgree === 20
        && !postBody.refuseDesc
      ) {
        ElMessage.error('请填写拒绝原因')
        return
      }

      $this.oneStepLoading = true
      OrderApi.Approval(postBody, true)
        .then(result => {
          $this.oneStepLoading = false
          const { code, msg } = result
          if (code === 1) {
            $this.getData()
            ElMessage.success(msg)
          } else {
            ElMessage.error(msg)
          }
        }).catch(error => {
          $this.oneStepLoading = false
        })
    },
    ywyThTwoStep(e) {
      //退货退款-业务员第二次审核
      const $this = this
      const postBody = {
        orderRefundId: e,
        isAgree: $this.form.isAgree,
        refuseDesc: $this.form.refuseDesc,
        refundMoney: $this.form.refundMoney
      }
      if (postBody.isAgree === 20
        && !postBody.refuseDesc
      ) {
        ElMessage.error('请输入拒绝原因')
        return
      }
      if (postBody.isAgree === 10
        && postBody.refundMoney <= 0
      ) {
        ElMessage.error('退款金额不合法')
        return
      }
      console.log('pobody', postBody)
      $this.oneStepLoading = true
      OrderApi.ShAudit(postBody, true)
        .then(result => {
          $this.oneStepLoading = false
          const { code, msg } = result
          if (code === 1) {
            $this.getData()
            ElMessage.success(msg)
          } else {
            ElMessage.error(msg)
          }
        }).catch(error => {
          $this.oneStepLoading = false
        })
    },
    /*审核*/
    onSubmit(e) {
      // 用户发起退款退货，业务员第一步审核

      /*
       用户发起退货退款->业务员审核(填写信息)->同意->业务员退款审核->财务审核->结束
                     ->业务员审核(填写信息)->拒绝->结束 
      */
      let self = this;
      let form = self.form;
      let orderRefundId = e;
      const json = {
        isAgree: form.isAgree,
        addressId: form.addressId,
        refuseDesc: form.refuseDesc,
        orderRefundId: orderRefundId,
        refundMoney: form.refundMoney,
      }
      if (Number(form.isAgree) === 10) {
        //检查地址
        if (!json.addressId) {
          ElMessage.error('请选择退货地址')
          return
        }
        self.postOneAudit(json)
      } else {
        if (!json.refuseDesc) {
          ElMessage.error('拒绝原因不能为空')
          return
        }
        self.postOneAudit(json)
      }

      // // type = 30 退款 10 退货退款
      // if (this.detail.type === 30
      //   && json.refundMoney <= 0
      // ) {
      //   ElMessage.error('退款金额不合法')
      //   return
      // }

      // if (json.isAgree === 20 &&
      //   !json.refuseDesc
      // ) {
      //   ElMessage.error('请输入拒绝原因')
      //   return
      // }

      // console.log('业务员审核', json)

      // return
      // self.btnLoading = true
      // OrderApi.Approval(json, true)
      //   .then((data) => {
      //     ElMessage({
      //       message: "恭喜你，操作成功",
      //       type: "success",
      //     });
      //     self.btnLoading = false
      //     this.getData();
      //   })
      //   .catch((error) => {
      //     self.btnLoading = false
      //   });
    },
    postOneAudit(json) {
      const self = this
      self.btnLoading = true
      OrderApi.Approval(json, true)
        .then((data) => {
          ElMessage({
            message: "恭喜你，操作成功",
            type: "success",
          });
          self.btnLoading = false
          this.getData();
        })
        .catch((error) => {
          self.btnLoading = false
        });
    },
    /*确认收货退款*/
    refundMoney(e) {
      // 用户发货后，商家 确认收货退款
      let self = this;
      console.log(self.money.refundMoney, "refundMoney");
      let form = {};
      // let param = self.deliver;
      // if (param.sendExpressId == "" && self.detail.type == 20) {
      //   ElMessage.error("请选择物流公司");
      //   return;
      // }
      // if (param.sendExpressNo == "" && self.detail.type == 20) {
      //   ElMessage.error("请填写物流单号");
      //   return;
      // }
      // if (self.detail.type == 20) {
      //   form.sendExpressId = param.sendExpressId;
      //   form.sendExpressNo = param.sendExpressNo;
      // }
      form.orderRefundId = e;
      form.refundMoney = self.form.refundMoney
      console.log('确认审核', form)
      OrderApi.receipt(form, true)
        .then((data) => {
          ElMessage({
            message: "恭喜你，操作成功",
            type: "success",
          });
          this.getData();
        })
        .catch((error) => { });
    },

    /*取消*/
    cancelFunc() {
      this.$router.back(-1);
    },
  },
};
</script>
<style>
.apply-reason {
  padding: 16px;
  background: #fff4f4;
  border: 1px solid #f6e6e6;
}

.apply-reason-box .pic {
  width: 100px;
  height: 100px;
  margin-right: 4px;
  border: 1px solid #d1d5dd;
}

.apply-reason-box .pic img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
